﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KarReq.Domain.Abstract;
using KarReq.Domain.Entities;
using System.Data;

namespace KarReq.Domain.Concrete
{
    public class EFKaraokeTrackRepository : IKaraokeTrackRepository
    {
        private EFDbContext context = new EFDbContext();

        public IQueryable<KaraokeTrack> KaraokeTracks
        {
            get { return context.KaraokeTracks; }
        }

        public IQueryable<Request> Requests
        {
            get { return context.Requests; }
        }

        public IQueryable<User> Users
        {
            get { return context.Users; }
        }

        public void SaveUser(User user)
        {
            // Add User
            if (user.UserID == 0)
            {
                context.Users.Add(user);
            }
            // Modify User
            else
            {
                context.Entry(user).State = EntityState.Modified;
            }
            context.SaveChanges();
        }

        public void DeleteUser(User user)
        {
            context.Users.Remove(user);
            context.SaveChanges();
        }

        public void SaveRequest(Request request)
        {
            if (request.RequestID == 0)
            {
                User user = context.Users.First(u => u.UserID == request.UserID);
                user.Requests.Add(request);
            }
            else
            {
                // No editing of requests
            }
            context.SaveChanges();
        }

        public void DeleteRequest(Request request)
        {
            context.Requests.Remove(request);
            context.SaveChanges();
        }

        public void ClearRequests(User user)
        {
            for (int i = user.Requests.Count; i > 0; i--)
            {
                Request request = context.Requests.First(r => r.UserID == user.UserID);
                context.Requests.Remove(request);
                context.SaveChanges();
            }
        }
    }
}
